﻿#include <iostream>
#include <vector>
using namespace std;


class Solution
{
    int tmp[50010];
public:
    // 493. 翻转对
    int reversePairs(vector<int>& nums)
    {
        return mergeSort(nums, 0, nums.size() - 1);
    }

    int mergeSort(vector<int>& nums, int left, int right)
    {
        if (left >= right)
            return 0;

        int ret = 0;
        // 1、根据中间元素划分区域
        int mid = (left + right) >> 1;
        // 2、统计左右两侧翻转对
        ret += mergeSort(nums, left, mid);
        ret += mergeSort(nums, mid + 1, right);

        int cur1 = left, cur2 = mid + 1, i = left;
        // 3、计算翻转对数量
        while (cur2 <= right)
        {
            // nums[cur1] <= 2 * nums[cur2]
            while (cur1 <= mid && nums[cur2] >= nums[cur1] / 2.0)
                cur1++;
            if (cur1 > mid)
                break;
            ret += mid - cur1 + 1;
            cur2++;
        }

        // 4、合并两个有序数组
        cur1 = left, cur2 = mid + 1;
        while (cur1 <= mid && cur2 <= right)
            tmp[i++] = nums[cur1] <= nums[cur2] ? nums[cur1++] : nums[cur2++];
        while (cur1 <= mid)
            tmp[i++] = nums[cur1++];
        while (cur2 <= right)
            tmp[i++] = nums[cur2++];

        for (int j = left; j <= right; j++)
            nums[j] = tmp[j];

        return ret;
    }
};

int main()
{
    vector<int> v{ 1,3,2,3,1 };
    Solution().reversePairs(v);

    return 0;
}